import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import OpenAI from 'openai';
import { BubbleModule, InputComponent, MarkdownCardModule } from '@matechat/ng';
@Component({
  selector: 'app-root',
  imports: [CommonModule, BubbleModule, InputComponent, MarkdownCardModule],
  templateUrl: './app.html',
  styleUrl: './app.scss',
})
export class App {
  inputValue = '';
  messages: any = [];
  newPage = true;
  theme = 'light';
  questionList = [
    '帮我写一篇文章',
    '你可以帮我做些什么？',
    '帮我写一个快速排序',
    '使用 js 格式化时间',
  ];
  avatarConfig = {
    imgSrc: 'https://matechat.gitcode.com/png/demo/userAvatar.svg',
  };
  modelAvatar = {
    imgSrc: 'https://matechat.gitcode.com/logo.svg',
  };
  client = new OpenAI({
    apiKey: 'sk-qddptrhspowhfrpenazqpbemctraeivkhekmfyvastozlpml', // 模型APIKey
    baseURL: 'https://api.siliconflow.cn/v1', // 模型API地址
    dangerouslyAllowBrowser: true,
  });

  fetchData = async (ques: any) => {
    this.messages.push({
      from: 'model',
      content: '',
      avatarConfig: { name: 'model' },
      id: '',
      loading: true,
    });
    const completion = await this.client.chat.completions.create({
      model: 'Qwen/Qwen2.5-72B-Instruct', // 替换为自己的model名称
      messages: [{ role: 'user', content: ques }],
      stream: true, // 为 true 则开启接口的流式返回
    });
    for await (const chunk of completion) {
      this.messages[this.messages.length - 1].loading = false;
      const content = chunk.choices[0]?.delta?.content || '';
      const chatId = chunk.id;
      this.messages[this.messages.length - 1].content += content;
      this.messages[this.messages.length - 1].id = chatId;
    }
  };

    themeChange = () => {
    if (this.themeService) {
      this.theme =
        this.themeService.currentTheme.id === 'infinity-theme'
          ? 'light'
          : 'dark';
    }
  };
themeService: any;
  ngOnInit() {
    if (typeof window !== 'undefined') {
      this.themeService = (window as any)['devuiThemeService'];
    }
    this.themeChange();
    if (this.themeService && this.themeService.eventBus) {
      this.themeService.eventBus.add('themeChanged', this.themeChange);
    }
  }

  onSubmit = (evt: any) => {
    this.newPage = false;
    this.inputValue = '';
    // 用户发送消息
    this.messages.push({
      from: 'user',
      content: evt,
    });
    // 调用模型接口
    this.fetchData(evt);
    // setTimeout(() => {
    //   // 模型返回消息
    //   this.messages.push({
    //     from: 'model',
    //     content: evt,
    //   });
    // }, 200);
  };
}
